import canvasAbstract from "./canvasAbstract"
import config from "../../config"
import model from "../model/enemy"
import bigTankModel from "../model/bigTank"
import redTankModel from "../model/redTank"
import greenTankModel from "../model/greenTank"
import quickTankModel from "../model/quickTank"

class enemy extends canvasAbstract implements ICanvas {
  currentModel = 0
  intervalId = null

  constructor() {
    super('enemy')
  }

  render(): void {
    this.createModels()
    this.beginRenderModels()
    // @ts-ignore
    this.intervalId = setInterval(() => super.renderModels(), config.timeout)
  }

  model(): ModelConstructor {
    return model
  }

  num(): number {
    return config.enemy.num
  }

  stop(): void {
    // @ts-ignore
    clearInterval(this.intervalId)
  }

  // 生成敌方坦克模型实例
  protected createModels() {
    let pos: { x: number, y: number } = {x: 0, y: 0}
    // 出生点分布在五个地方 可重叠
    const birthPoint = this.currentModel % 5
    if (birthPoint === 1) {
      pos.x = 0
    } else if (birthPoint === 2) {
      pos.x = config.canvas.width * 0.25
    } else if (birthPoint === 3) {
      pos.x = config.canvas.width * 0.5
    } else if (birthPoint === 4) {
      pos.x = config.canvas.width * 0.75
    } else if (birthPoint === 0) {
      pos.x = config.canvas.width - config.model.width
    }
    // 固定在第一行出现敌方坦克
    pos.y = 0
    // 创建实例
    const random = Math.random()
    let instance
    if (random > 0.7) {
      // 红坦克和快速坦克随机
      let randomTank = Math.random()
      if (randomTank >= 0.5) {
        instance = new quickTankModel(pos)

      } else {
        instance = new redTankModel(pos)
      }
    } else if (random > 0.5) {
      instance = new bigTankModel(pos)
    } else if (random > 0.4) {
      instance = new greenTankModel(pos)
    } else {
      instance = new model(pos)
    }
    // 保存实例
    this.models.push(instance)
  }

  // 开始渲染模型 让坦克不至于一次全部出现
  protected beginRenderModels() {
    // 一个一个出现
    let timeout = setInterval(() => {
      // 渲染数小于总实例时
      if (this.currentModel < config.enemy.num - 1) {
        this.currentModel++
        this.createModels()
      }
      // 全部出现后清除定时器
      if (this.currentModel === config.enemy.num - 1) {
        // 保持渲染坦克
        clearInterval(timeout)
      }
    }, 1500)
  }
}

export default new enemy()
